package com.newly.common.core.utils.file;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.newly.common.base.exception.FileClientException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @program: file-client
 * @remark: 本地文件处理客户端
 * @author: guan
 * @create: 2021-11-05 15:20
 */
public class LocalClient extends AbstractFileClient implements IFileClient {

    @Override
    public String upload(String fileName, InputStream fileStream, String relativePath) {
        if (ObjectUtil.isEmpty(fileStream)) {
            throw new FileClientException("文件流不能为空");
        }
        if (StrUtil.isBlank(relativePath)) {
            throw new FileClientException("目标路径不能为空");
        }

        // 根据规则得到文件名
        fileName = this.handleFileName(fileName);

        // 得到完整路劲
        relativePath = this.handleFilePath(this.localRootPath, relativePath);

        File destFile = new File(relativePath);
        if (!destFile.exists()) {
            destFile.mkdirs();
        }

        // 目标文件
        relativePath = String.format("%s/%s", destFile.getAbsolutePath(), fileName);
        byte[] flush = new byte[1024];
        int len = -1;
        OutputStream os = null;
        try {
            os = new FileOutputStream(relativePath);
            while ((len = fileStream.read(flush)) != -1) {
                os.write(flush, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new FileClientException("文件流处理失败:" + e);
        } finally {
            closeFd(fileStream, os);
        }

        return this.realResPath(relativePath, fileName);
    }

    @Override
    public String upload(String fileName, String srcFile, String relativePath) {
        return this.upload(fileName, this.getFileStream(srcFile), relativePath);
    }

    @Override
    public String upload(String fileName, MultipartFile multipartFile, String relativePath) {
        return this.upload(fileName, this.getFileStream(multipartFile), relativePath);
    }

    @Override
    public String download(String fileName, String relativePath) {
        return null;
    }

    @Override
    public String download(String fileName) {
        return null;
    }

}
